package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.mkt.InquiryProDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.BidCurrencyDomain;
import top.infopub.mgr.mkt.domain.InquiryProDomain;
import top.infopub.mgr.mkt.jsonvo.InquiryProJsonVo;
import top.infopub.mgr.mkt.service.*;
import top.infopub.mgr.mkt.vo.InquiryProVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.*;
import top.infopub.model.om.PaymentApply;
import top.infopub.model.om.PaymentApplyDetail;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 资格预审管理
 * @author wangw
 * @version 2020年1月9日
 * @see InquiryProjectController
 * @since
 */
@Controller
@RequestMapping("/inquiryPro")
public class InquiryProjectController extends GenericFlowController {

    @Autowired
    private InquiryProService inquiryProService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private BidAnalysisService bidAnalysisService;

    /**
     * 资格预审列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-inquiryPro-list";
    }

    /**
     * 资格预审列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<BidCurrencyDomain> queryDataByCondition( ParamPage paramPage,String proCode,String proName,String hrOrgId,
                                                          String processStatus,String dates,String staffId,String minAmt,String maxAmt) {

        InquiryProVo inquiryProVo=new InquiryProVo();
        inquiryProVo.setProCode(proCode);
        inquiryProVo.setProName(proName);
        inquiryProVo.setHrOrgId(hrOrgId);
        inquiryProVo.setProcessStatus(processStatus);
        if (org.apache.commons.lang.StringUtils.isNotBlank(dates)) {
            inquiryProVo.setDates(dates);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(staffId)) {
            inquiryProVo.setStaffId(staffId);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(minAmt)) {
            inquiryProVo.setMinAmt(minAmt);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(maxAmt)) {
            inquiryProVo.setMaxAmt(maxAmt);
        }
        Page<BidCurrencyDomain> page = new Page<BidCurrencyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = inquiryProService.selectPageByDomainWhere(page, inquiryProVo);
        System.out.println("page:"+page);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 资格预审-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<InquiryProDomain> queryMyCheckDataByCondition(InquiryProVo inquiryProVo, ParamPage paramPage) {
        Page<InquiryProDomain> page = new Page<InquiryProDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (inquiryProVo.getEndDate() != null) {
            inquiryProVo.setEndDate(DateUtils.addDays(inquiryProVo.getEndDate(), 1));
        }
        //查询时，资格预审截止日期结束日期增加一天
        if (inquiryProVo.getInquiryEndDate() != null) {
            inquiryProVo.setInquiryEndDate(DateUtils.addDays(inquiryProVo.getInquiryEndDate(), 1));
        }
        inquiryProVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = inquiryProService.selectMyCheckByDomainWhere(page, inquiryProVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 资格预审-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可资格预审的预资格预审记录
        List<SetupPro> setupPros = setupProService.selectUsableSetupPro();
        request.setAttribute("setupPros", setupPros);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-inquiryPro-add";
    }

    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        InquiryPro inqPro = inquiryProService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        request.setAttribute("isThoughFlag", "0");
        if (inqPro != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), inqPro.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), inqPro.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(inqPro.getProcessId()) && inqPro.getProcessId().length() > 10) {
                request.setAttribute("processId", inqPro.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(inqPro.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), inqPro.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
            //如果审批通过，并且招标文件分析没有数据，开放保存和提交按钮
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), inqPro.getProcessStatus())) {
                BidAnalysis bidAna = bidAnalysisService.queryByProCode(inqPro.getProCode());
                if (bidAna == null) {
                    request.setAttribute("isAuditFlag", "1");
                    request.setAttribute("isThoughFlag", "1");
                }
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-prequalification-detail";
    }

    @RequestMapping("/queryDetailById")
    @ResponseBody
    public RspVo queryDetailById(String id) {
        //资格预审详情信息
        InquiryProJsonVo inqProJson = inquiryProService.queryDetailById(id);
        return RspVo.getSuccessResponse(inqProJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //资格预审审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    @RequestMapping("/toDetail")
    public String queryDetailById(HttpServletRequest request,String id){
        return "mkt/lay-inquiryPro-add";
    }

    /**
     * 资格预审-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        InquiryProVo inquiryPro = inquiryProService.selectById(id);
        request.setAttribute("inquiryPro", inquiryPro);
        //查询可资格预审的预资格预审记录
        List<SetupPro> setupPros = setupProService.selectUsableSetupPro();
        request.setAttribute("setupPros", setupPros);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-inquiryPro-copy";
    }

    /**
     * 编辑招标文件分析
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        InquiryProJsonVo inqProJson = JSON.parseObject(str, InquiryProJsonVo.class);
        InquiryProDto inqProDto = inqProJson.getInfo();
        //修改项目基础信息表-MKT_PROJECT_INFO
        ProjectInfo proInfo = new ProjectInfo();
        proInfo.setQualificationType(inqProDto.getQualificationType());

        //更新资格预审表-MKT_INQUIRY_PRO
        InquiryPro inquiryPro = new InquiryProVo();
        BeanUtils.copyProperties(inqProDto, inquiryPro);

        //更新投标信息表-MKT_BID_INFO
        BidInfo bidInfo = new BidInfo();

        //保存竞争对手单位名称(是否通过资审选择是填写的数据)-MKT_INQUIRY_COMPANY
        String[] companyArr = inqProJson.getCompnayArr();

        //更新付款申请-OM_PAYMENT_APPLY
        PaymentApply paymentApply = new PaymentApply();

        //更新付款申请明细-OM_PAYMENT_APPLY_DETAIL
        PaymentApplyDetail paymentApplyDetail = new PaymentApplyDetail();
        BeanUtils.copyProperties(inqProDto, paymentApplyDetail);

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(inqProJson.getFileAtt()!=null){
            String[] fileAtt = inqProJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, inqProDto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }

        //调用service进行数据库操作
        RspVo rspVo = inquiryProService.editDetail(inquiryPro, inqProDto, proInfo, bidInfo, paymentApply, paymentApplyDetail, companyArr, attachmentList, vo, submitType);
        return rspVo;
    }

    private InquiryProAtt createFileAtt(AuthorizationVO vo, String inquiryProId, String file) {
        //资料附件数组
        String[] fileAttStr = file.split("\\|");
        InquiryProAtt fileAtt = new InquiryProAtt();
        if(StringUtils.isNotEmpty(fileAttStr[2])){
            fileAtt.setId(fileAttStr[2]);
        }else{
            fileAtt.setId(IdFactory.getUUIDUpper());
        }
        fileAtt.setTypes(fileAttStr[0]);//附件类型
        fileAtt.setInquiryProId(inquiryProId);//项目id
        String fileName = fileAttStr[1].substring(0,fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 根据id查询营销策划记录
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getInquiryProById")
    @ResponseBody
    public Map<String, Object> getInquiryProById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            InquiryProVo inquiryProVo = inquiryProService.selectById(id);
            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//            inquiryProVo.setStaffName(staffInfo.getStaffName());
            map.put("inquiryProVo", inquiryProVo);
        }
        catch (Exception e) {
            log.error("查询资格预审记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if(StringUtils.isEmpty(types)){
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "inquiryProAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types+"|"+file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传资格预审附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
